﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TransactionManager.cs" company="CodePlex">
//   Copyright © CodePlex 2012
// </copyright>
// <summary>
//   Class in charge of handling transactions.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace DataFramework
{
    using System.Data;

    using DataFramework.Factories;

    /// <summary>
    /// Class in charge of handling transactions.
    /// </summary>
    public class TransactionManager
    {
        /// <summary>
        /// The connection that is distributed amongst the framework.
        /// </summary>
        private static readonly IDbConnection SharedConnection;

        /// <summary>
        /// Initializes static members of the <see cref="TransactionManager"/> class.
        /// </summary>
        static TransactionManager()
        {
            SharedConnection = DataProviderFactory.BuildConnection();
        }

        /// <summary>
        /// Gets the connection.
        /// </summary>
        /// <value>The connection.</value>
        internal static IDbConnection Connection
        {
            get
            {
                return SharedConnection;
            }
        }

        /// <summary>
        /// Gets the transaction.
        /// </summary>
        /// <value>The transaction.</value>
        internal static IDbTransaction Transaction { get; private set; }

        /// <summary>
        /// Starts the transaction.
        /// </summary>
        public static void StartTransaction()
        {
            SharedConnection.Open();
            Transaction = SharedConnection.BeginTransaction();
        }

        /// <summary>
        /// Commits the transaction.
        /// </summary>
        public static void CommitTransaction()
        {
            if (Transaction != null)
            {
                Transaction.Commit();
            }

            SharedConnection.Close();
        }

        /// <summary>
        /// Rolls back the transaction.
        /// </summary>
        public static void RollbackTransaction()
        {
            if (Transaction != null)
            {
                Transaction.Rollback();
            }

            SharedConnection.Close();
        }
    }
}
